package com.whf.android.jar.media;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.provider.Settings;


import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.bitmap.BitmapUtils;
import com.whf.android.jar.util.file.SdkVersionUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.whf.android.jar.view.item.WatermarkDrawable;

import java.io.FileOutputStream;

/**
 * 通过ContentObserver监听多媒体图片库资源的变化。
 * <p>当手机上有新的图片文件产生时都会通过MediaProvider类向图片数据库插入一条记录，
 * <p>以方便系统的图片库进行图片查询，可以通过ContentObserver接收图片插入事件，并获取插入图片的URI。
 *
 * @author qf
 * @version 1.0.2
 */
public final class MediaManage implements MediaContentObserver.IScreenshotCallBack {

    private ContentResolver mContentResolver;
    /*** 内部存储器内容观察者 **/
    private MediaContentObserver mInternalObserver;
    /*** 外部存储器内容观察者 **/
    private MediaContentObserver mExternaLObserver;

    private static class H {
        @SuppressLint("StaticFieldLeak")
        private static final MediaManage mediaManage = new MediaManage();
    }

    private MediaManage() {
    }

    public static MediaManage getInstance() {
        return H.mediaManage;
    }

    @SuppressLint("WrongConstant")
    public void init(ContentResolver contentResolver) {
        this.mContentResolver = contentResolver;
        LatteLogger.i("系统版本" + Build.VERSION.SDK_INT);
        HandlerThread mHandlerThread = new HandlerThread("content_observer");
        mHandlerThread.start();
        Handler mHandler = new Handler(mHandlerThread.getLooper());
        if (SdkVersionUtils.isR() && !Environment.isExternalStorageManager()) {
            //R以上的特殊存储权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + Latte.getApplicationContext().getPackageName()));
            Latte.getActivity().startActivityForResult(intent, 1255);
            return;
        }

        mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mHandler,
                mContentResolver, this);
        mExternaLObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mHandler,
                mContentResolver, this);
        register(SdkVersionUtils.isR());
    }

    /**
     * 断是否有储存权限
     */
    public boolean checkStoragePermission() {
        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        int result = ContextCompat.checkSelfPermission(Latte.getApplicationContext(), storagePermission);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 添加监听
     */
    private void register(boolean notifyForDescendants) {
        if (mContentResolver != null) {
            LatteLogger.i("添加监听");
            mContentResolver.registerContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    notifyForDescendants, mInternalObserver);
            mContentResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    notifyForDescendants, mExternaLObserver);
        }
    }

    /*/ 启动屏幕捕获
//    private void startScreenCapture(Handler mHandler) {
//       // 创建 ImageReader 用于接收截屏数据
//       ImageReader imageReader = ImageReader.newInstance(ScreenUtils.getAppScreenWidth(),
//                ScreenUtils.getAppScreenHeight(),
//                PixelFormat.RGBA_8888,
//                1);
//        // 注册 ImageReader 的监听器，用于接收截屏完成通知
//        imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
//            @Override
//            public void onImageAvailable(ImageReader reader) {
//                // 获取截屏数据并转换为 Bitmap 对象
//                LatteLogger.i("图片数据改变了");
//                // 从 ImageReader 获取图像数据
//                Image image = reader.acquireLatestImage();
//                if (image != null) {
//                    ByteBuffer byteBuffer = image.getPlanes()[0].getBuffer();
//                    byte[] bytes = new byte[byteBuffer.capacity()];
//                    byteBuffer.get(bytes);
//                    // 将图像数据转换为 Bitmap 对象
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
//                    // 在这里可以进行各种图像处理操作，例如缩放、旋转、裁剪等
//                    //叠加水印图片
//                    final Bitmap outBitmap = BitmapUtils.addWatermark(bitmap, new WatermarkDrawable().getBitmap());
//                    Latte.getHandler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                // 替换截图
//                                FileOutputStream out = new FileOutputStream("/path/to/your/image.jpg");
//                                outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
//                                out.close();
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                                LatteLogger.e(e.getMessage());
//                            }
//                        }
//                    }, 555);
//                    // 处理完成后，记得释放资源
//                    image.close();
//                }
//            }
//        }, mHandler);
//    }
    */

    /**
     * 移除监听
     */
    public void unregister() {
        if (mContentResolver != null && mInternalObserver != null && mExternaLObserver != null) {
            mContentResolver.unregisterContentObserver(mInternalObserver);
            mContentResolver.unregisterContentObserver(mExternaLObserver);
        }
    }

    @Override
    public void screenshotTaken(final String path) {
        final Bitmap bitmap = BitmapUtils.decodeImage(path);
        if (bitmap == null) {
            LatteLogger.e("bitmap is null");
            return;
        }
        //叠加水印图片
        final Bitmap outBitmap = BitmapUtils.addWatermark(bitmap, new WatermarkDrawable().getBitmap());
        if (outBitmap == null) {
            LatteLogger.e("叠加水印图片 is null");
            return;
        }
        Latte.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    // 替换截图
                    FileOutputStream out = new FileOutputStream(path);
                    outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.close();
                    // 提示
                    ToastUtils.showShort("截屏成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    LatteLogger.e(e.getMessage());
                }
            }
        }, 222);
    }

}
